var QQMapWX = require('../../resource/utils/qqmap-wx-jssdk.js');
var qqmapsdk;
const app = getApp();
Page({
  data: {
    goods_id:"",
    sonsList:"",
    specification_id: '',
    minusStatus: 'disabled',
    num: 1,
    block: 0,
    data: [],
    dataSon: [],
    good_image:"",
    nowprice: '',
    oldprice: "",
    stock:"",
    jx_goods:"",
    page:1,
    limit:10,
    getPosution:'',
    tabbar:{},
    showView: true,
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    cardCur: 0,
    tower: [],
    moRenShop:"",
    nomorelist: true,
    latestGoods:'',
    recommendClass:"",
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar
  },
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },

  // 用于实现点击“核算”时，来显示与隐藏整个“conts”，这一部分其实是利用了面板的显示与隐藏功能  
  change: function () {
    let that = this;
    that.setData({
      showView: (!that.data.showView)
    })
  },
  close: function () {
    let that = this;
    that.setData({
      showView: (!that.data.showView)
    })
  },
  /* 点击减号 */
  bindMinus: function () {
    var num = this.data.num;
    // 如果大于1时，才可以减
    if (num > 1) {
      num--;
    }
    // 只有大于一件的时候，才能normal状态，否则disable状态
    var minusStatus = num <= 1 ? 'disabled' : 'normal';
    // 将数值与状态写回
    this.setData({
      num: num,
      minusStatus: minusStatus
    });
  },
  inputTyping: function (e) {
    var that = this;
    var reg = /^[1-9]\d*$/;
    var minusStatus = num < 1 ? 'disabled' : 'normal';
    if (reg.test(e.detail.value)) {
      var num = e.detail.value;
      var index = that.data.block;
      var data = that.data.sonsList;
      var goods_inventory = data[index]['goods_inventory'];
      if (num > goods_inventory) {
        num = goods_inventory;
      }

      that.setData({
        num: num,
        minusStatus: minusStatus
      });
    } else {
      that.setData({
        num: 1,
        minusStatus: minusStatus
      });
    }
  },
  /* 输入框事件 */
  bindManual: function (e) {
    var num = e.detail.value;
    // 将数值与状态写回
    this.setData({
      num: num
    });
  },
  /* 点击加号 */
  bindPlus: function () {
    var that = this;
    var num = that.data.num;
    num++;
    var index = that.data.block;
    var data = that.data.sonsList;
    var goods_inventory = data[index]['goods_inventory'];
    if (num > goods_inventory) {
      num = goods_inventory;
    }
    var minusStatus = num < 1 ? 'disabled' : 'normal';
    that.setData({
      num: num,
      minusStatus: minusStatus
    });
  },
  //商品规格选择
  guigecheck: function (data) {
    var that = this;
    console.log(data)
    that.setData({
      // moGuiGe: data._relatedInfo.anchorRelatedText,
      specification_id: data.currentTarget.dataset.specificationid
    })
    var index = data.currentTarget.dataset.id;
    var data = that.data.data;
    var dataSon = data.son;
    var guigearr = dataSon[index];
    var num = 1;

    that.setData({
      num: num,
      block: index,
      good_image: app.globalData.url + guigearr["goods_image"],
      nowprice: guigearr['goods_present_price'],
      oldprice: guigearr['goods_original_price'],
      stock: guigearr["goods_inventory"],
    })
  },
  // 商品规格确认加入购物车
  addShop: function (e) {
    const value = wx.getStorageSync('openid')
    this.hideModal(e)
    // console.log(this.data.num)
    var that = this;
    var form_id = e.detail.formId
    app.util.request({
      url: 'admin/WxGoodsApi/formId',
      method: 'post',
      data: {
        form_id: form_id,
        open_id: value
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res)
        if (res.data.code == 0) {
          console.log("formId发送成功")
        }

      },
      fail: function (res) {
        wx.showToast({
          title: '服务器响应失败',
          icon: 'none',
          duration: 2000
        })
      }
    });
    app.util.request({
      url: 'admin/WxGoodsApi/shopcar',
      data: {
        goods_id: that.data.goods_id,
        goods_num: that.data.num,
        specification_id: that.data.specification_id,
        uid: value
      },
      method: 'post',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        if (res.data.code == 0) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          })
          var dataNum = parseInt(that.data.num)
          app.globalData.tabbar.list[2]['dott'] += dataNum;
          app.setData();
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail: function (res) {
        wx.showToast({
          title: "服务器无响应",
          icon: 'none',
          duration: 2000
        })
      }

    });

  },
  // 加号logo 获取规格
  addHao(e){
    var that=this
    that.setData({
      num:1
    })
    // console.log(e.currentTarget.dataset.index)
    var index = e.currentTarget.dataset.index
    console.log(index)
    // 为您精选
    app.util.request({
      url: 'admin/WxGoodsApi/jx_goods',
      data: {
        page: this.data.page,
        limit: this.data.limit,
      },
      method: 'post',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res)
        var data = res.data.data
        if (res.data.code == 0) {
          var jx_goods_id=index
          console.log(jx_goods_id)
        // 二次 start
          app.util.request({
            url: 'admin/WxGoodsApi/goodsInfo',
            data: {
              id: jx_goods_id
            },
            method: 'post',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
              console.log(res)
              if (res.data.code == 0) {
                var sonsList = res.data.data.son;
                 // 如果只有一条规格，直接加入购物车
                if (sonsList.length==1){
                  console.log(jx_goods_id)
                  var specification_id = res.data.data.son[0].id
                  const value = wx.getStorageSync('openid')
                  app.util.request({
                    url: 'admin/WxGoodsApi/shopcar',
                    data: {
                      goods_id: jx_goods_id,
                      goods_num: that.data.num,
                      specification_id: specification_id,
                      uid: value
                    },
                    method: 'post',
                    header: {
                      'content-type': 'application/x-www-form-urlencoded'
                    },
                    success: function (res) {
                      console.log(res)
                      if (res.data.code == 0) {
                        wx.showToast({
                          title: res.data.msg,
                          icon: 'none',
                          duration: 2000
                        })
                        app.globalData.tabbar.list[2]['dott'] = app.globalData.tabbar.list[2]['dott'] + 1;
                        app.setData();
                      } else {
                        wx.showToast({
                          title: res.data.msg,
                          icon: 'none',
                          duration: 2000
                        })
                      }
                    },
                    fail: function (res) {
                      wx.showToast({
                        title: "服务器无响应",
                        icon: 'none',
                        duration: 2000
                      })
                    }

                  });
                  return;


                }else{
                  that.showModal(e)
                  console.log(res.data.data.son[0].id)
                  that.setData({
                    sonsList: sonsList,
                    goods_id: jx_goods_id,
                    specification_id: res.data.data.son[0].id
                  })
                  var data = res.data.data
                  for (var i = 0; i < data.length; i++) {
                    data[i]['goods_list_image'] = app.globalData.url + data[i]['goods_list_image'];
                  }
                  var str = data.goods_rotation;
                  var strs = new Array(); //定义一数组 
                  strs = str.split(","); //字符分割
                  for (var i = 0; i < strs.length; i++) {
                    strs[i] = app.globalData.url + strs[i];
                  }
                  var dataSon = data.son
                  that.setData({
                    data: data,
                    dataSon: dataSon,
                    good_image: app.globalData.url + dataSon[0]["goods_image"],
                    nowprice: dataSon[0]['goods_present_price'],
                    oldprice: dataSon[0]['goods_original_price'],
                    stock: dataSon[0]["goods_inventory"],
                  })
                }
                
              } else {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none',
                  duration: 2000
                })
                setTimeout(function () {
                  wx.reLaunch({
                    url: './index',
                  })
                }, 2000)
              }

            },
            fail: function (res) {
              wx.showToast({
                title: res.data.msg,
                icon: 'none',
                duration: 2000
              })
            }
          });
        // 二次end
        }
      },
      fail: function (res) {
        wx.showToast({
          title: '服务器响应失败',
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  onLoad(){
    var that = this;
    const value = wx.getStorageSync('openid');
    app.changeTabBar();
    wx.setNavigationBarTitle({
      title: '蜂语网络'
    }),
    this.towerSwiper('tower');
    qqmapsdk = new QQMapWX({ key: '4B7BZ-LD46U-C7FVV-4ZFNG-YVZT3-7MFGJ' });
    wx.getLocation({
      type: 'wgs84',
      success(res){
        const latitude = res.latitude
        const longitude = res.longitude
        that.qqmap(latitude + ',' + longitude);
      }
    })
    //轮播
    app.util.request({
      url: 'admin/WxGoodsApi/rotation',
      method: 'post',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        if(res.data.code==0){
          var datalun = res.data.data
          for (var i = 0; i < datalun.length; i++) {
            datalun[i]['rotation_image'] = app.globalData.url + datalun[i]['rotation_image'];
          }
          that.setData({
            tower: datalun
          })
        }
        
      },
      fail: function (res) {
        wx.showToast({
          title: '服务器响应失败',
          icon: 'none',
          duration: 2000
        })
      }
    });
    // 默认门店
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        const latitude = res.latitude
        const longitude = res.longitude
        app.util.request({
          url: 'admin/WxGoodsApi/nearby_store',
          data: {
            uid:value,
            longitude: latitude,
            latitude: longitude
          },
          method: 'post',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function (res){
            if(res.data.code==0){
              var data = res.data.data;
              for (var c = 0; c < data.length; c++) {
                if (data[c].default_shop === 1) {
                  that.setData({
                    moRenShop: data[c].shop_name
                  })
                }
              }
              if (that.data.moRenShop == "") {
                that.setData({
                  moRenShop: data[0].shop_name
                })
              }
            }
            
          },
          fail: function (res) {
            wx.showToast({
              title: '服务器响应失败',
              icon: 'none',
              duration: 2000
            })
          }
        });
      }
    });
    // 为您精选
    app.util.request({
      url: 'admin/WxGoodsApi/jx_goods',
      data: {
        page: this.data.page,
        limit: this.data.limit,
      },
      method: 'post',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        // console.log(res)
        var data = res.data.data
        if(res.data.code==0){
          if (!data) {
            that.setData({
              nomorelist: true
            })
          } else {
            for (var i = 0; i < data.length; i++) {
              data[i]['goods_list_image'] = app.globalData.url + data[i]['goods_list_image'];
            }
            that.setData({
              jx_goods: data
            })
          }
        }
       
        
      },
      fail: function (res) {
        wx.showToast({
          title: '服务器响应失败',
          icon: 'none',
          duration: 2000
        })
      }
    });
    // 每日新品二个图
    app.util.request({
      url: 'admin/WxGoodsApi/latestGoods',
      data: {},
      method: 'post',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res)
        var data = res.data.data
        if (res.data.code == 0) {

            for (var i = 0; i < data.length; i++) {
              data[i]['rotation_image'] = app.globalData.url + data[i]['rotation_image'];
            }
            that.setData({
              latestGoods: data
            })
       
        }


      },
      fail: function (res) {
        wx.showToast({
          title: '服务器响应失败',
          icon: 'none',
          duration: 2000
        })
      }
    });
    // 精品分类5个
    app.util.request({
      url: 'admin/WxGoodsApi/recommendClass',
      data: {},
      method: 'post',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        // console.log(res)
        var data = res.data.data
        if (res.data.code == 0) {
          for (var i = 0; i < data.length; i++) {
            data[i]['logo'] = app.globalData.url + data[i]['logo'];
            }
        
            that.setData({
              recommendClass: data
            })
       
        }


      },
      fail: function (res) {
        wx.showToast({
          title: '服务器响应失败',
          icon: 'none',
          duration: 2000
        })
      }
    });

  },
  onShow:function(){
    const value = wx.getStorageSync('openid');
    app.util.request({
      url: 'admin/WxGoodsApi/shopcarList',
      method: 'post',
      data: {
        uid: value
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        var data = res.data.data;
        var num = 0;
        if (data === undefined || data.length == 0) {
          app.globalData.tabbar.list[2]['dott'] = num;
          app.setData();
        }else{
          for (var i = 0; i < data.length; i++) {
            num += data[i]['goods_num'];
          }
          app.globalData.tabbar.list[2]['dott'] = num;
          app.setData();
        }
        
      },
      fail: function (res) {
        wx.showToast({
          title: '服务器响应失败',
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  qqmap: function (location){
    var _this = this;
    qqmapsdk.reverseGeocoder({

      location: location || '', 
      success: function (res){
        // console.log(res.result.address);
        _this.setData({
          getPosution: app.globalData.getPosution= res.result.address
        })
      },
      fail: function (error) {
        console.error(error);
      }
    })
  },
  DotStyle(e) {
    this.setData({
      DotStyle: e.detail.value
    })
  },
  // cardSwiper
  cardSwiper(e) {
    this.setData({
      cardCur: e.detail.current
    })
  },
  // towerSwiper
  // 初始化towerSwiper
  towerSwiper(name) {
    let list = this.data[name];
    for (let i = 0; i < list.length; i++) {
      list[i].zIndex = parseInt(list.length / 2) + 1 - Math.abs(i - parseInt(list.length / 2))
      list[i].mLeft = i - parseInt(list.length / 2)
    }
    this.setData({
      towerList: list
    })
  },

  // towerSwiper触摸开始
  towerStart(e) {
    this.setData({
      towerStart: e.touches[0].pageX
    })
  },
  tabbar(e){
    app.tabbar(e);
  },
  // towerSwiper计算方向
  towerMove(e) {
    this.setData({
      direction: e.touches[0].pageX - this.data.towerStart > 0 ? 'right' : 'left'
    })
  },

  // towerSwiper计算滚动
  towerEnd(e) {
    let direction = this.data.direction;
    let list = this.data.towerList;
    if (direction == 'right') {
      let mLeft = list[0].mLeft;
      let zIndex = list[0].zIndex;
      for (let i = 1; i < list.length; i++) {
        list[i - 1].mLeft = list[i].mLeft
        list[i - 1].zIndex = list[i].zIndex
      }
      list[list.length - 1].mLeft = mLeft;
      list[list.length - 1].zIndex = zIndex;
      this.setData({
        towerList: list
      })
    } else {
      let mLeft = list[list.length - 1].mLeft;
      let zIndex = list[list.length - 1].zIndex;
      for (let i = list.length - 1; i > 0; i--) {
        list[i].mLeft = list[i - 1].mLeft
        list[i].zIndex = list[i - 1].zIndex
      }
      list[0].mLeft = mLeft;
      list[0].zIndex = zIndex;
      this.setData({
        towerList: list
      })
    }
  },
  /**
 * 页面上拉触底事件的处理函数
 */
  onReachBottom: function (){// 精选++
    var page = this.data.page;
    var pages = ++page;
    var that = this;
    that.setData({
      page: pages
    })
    app.util.request({
      url: 'admin/WxGoodsApi/jx_goods',
      data: {
        page: pages,
        limit: this.data.limit,
      },
      method: 'post',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        var data = res.data.data;
        if (data === undefined || data.length == 0){
          that.setData({
            nomorelist: false
          })
        }else{
          for (var i = 0; i < data.length; i++){
            data[i]['goods_list_image'] = app.globalData.url + data[i]['goods_list_image'];
          }
          var jx_goods = that.data.jx_goods;
          for (var i = 0; i < data.length; i++){
            jx_goods.push(data[i]);
          }
          that.setData({
            jx_goods: jx_goods,
          })
        }
      },
      fail:function(res){
        wx.showToast({
          title: '服务器响应失败',
          icon: 'none',
          duration: 2000
        })
      }
    });
    }


});